package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.SMSUtils;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;


@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 发送手机验证码的短信
     * @param request
     * @param user
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(HttpServletRequest request, @RequestBody User user){
        //获取手机号
        String phone = user.getPhone();
        if(StringUtils.isNotEmpty(phone)){
            //生成随机验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("code = {}",code);
            //调用阿里云短信服务发送短信
//            SMSUtils.sendMessage("瑞吉外卖","SMS_281410230",phone,code);
            //将生成的验证码保存到Session中
            request.getSession().setAttribute(phone,code);
            return R.success("发送成功!");

        }

        return R.error("短信发送失败!");
    }

    /**
     * 登录
     * @param request
     * @param map
     * @return
     */
    @PostMapping("/login")
    public R<User> login(HttpServletRequest request, @RequestBody Map map){
        log.info(map.toString());
        //获取手机号
        String phone = map.get("phone").toString();
        //获取验证码
        String code = map.get("code").toString();
        //从session中获取保存的验证码
        Object attribute = request.getSession().getAttribute(phone);
        //进行验证码的比对
        if(attribute!=null&&attribute.equals(code)){
            //比对成功,登录成功
            //如果是新用户,自动注册
            LambdaQueryWrapper<User> lqw =new LambdaQueryWrapper<>();
            lqw.eq(User::getPhone,phone);
            User user = userService.getOne(lqw);
            if(user==null){
                //新用户,注册
                 user = new User();
                 user.setPhone(phone);
                 userService.save(user);
            }
            request.getSession().setAttribute("user",user.getId());
            return R.success(user);
        }

        return R.error("登录失败!");
    }
}
